package com.jeomo.mem.starter.service.impl;

import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.util.RedisUtil;
import com.jeomo.masterdata.starter.constant.MemberRedisKey;
import com.jeomo.mem.starter.entity.MemberPointsActivity;
import com.jeomo.mem.starter.mapper.MemberPointsActivityMapper;
import com.jeomo.mem.starter.service.IMemPointsActivityInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author:Jackpot
 * @create 2020-09-21 17:21
 * @description:
 */
@Service
@Transactional
public class MemPointsActivityInfoServiceImpl extends BaseServiceImpl<MemberPointsActivityMapper, MemberPointsActivity>
        implements IMemPointsActivityInfoService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String USE_LEVEL = "use_level";
    private final String USE_RANGE = "use_range";
    private final String START_FLAG = "start_flag";

    private final String CACHE_KEY = MemberRedisKey.ACTIVITY_HASH_KEY;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private MemberPointsActivityMapper memberPointsActivityMapper;

    @Override
    public List<MemberPointsActivity> getAllPointsActivities() {
        return memberPointsActivityMapper.getAllPointsActivities();
    }

    @Override
    public Map<Object, Object> queryCache() {

        Map<Object, Object> cacheMap = redisUtil.hmget(CACHE_KEY);
        if (!cacheMap.isEmpty()) return cacheMap;
        refreshCache();
        cacheMap = redisUtil.hmget(CACHE_KEY);
        return cacheMap;
    }

    @Override
    public boolean save(MemberPointsActivity activity) {

        boolean save = super.save(activity);
        boolean hset = redisUtil.hset(CACHE_KEY, activity.getCode(), activity.getName());
        return save&&hset;
    }

    /**
     * 删除缓存key,读取数据库,加入缓存
     */
    @Override
    public void refreshCache(){
        redisUtil.del(CACHE_KEY);
        List<MemberPointsActivity> allPointsActivities = memberPointsActivityMapper.getAllPointsActivities();
        for(MemberPointsActivity activity : allPointsActivities){
            redisUtil.hset(CACHE_KEY, activity.getCode(), activity.getName());
        }
    }

    @PostConstruct
    public void init(){
        logger.info("Redis缓存初始化:[会员积分活动]");
        if (redisUtil.hasKey(CACHE_KEY)) return;
        refreshCache();
    }

}
